#!/bin/bash
set -e

echo "=== K8s Podman Demo 部署开始 ==="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查工具是否安装
check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 未安装，请先安装 $1"
        exit 1
    fi
}

# 加载镜像到 Kind 集群函数
load_image_to_kind() {
    local image=$1
    local cluster_name=$2
    
    log_info "加载镜像 $image 到 Kind 集群 $cluster_name..."
    
    # 方法1: 尝试直接加载（如果 Podman 提供程序工作）
    if KIND_EXPERIMENTAL_PROVIDER=podman kind load docker-image "$image" --name "$cluster_name" 2>/dev/null; then
        log_info "✓ 直接加载成功"
        return 0
    fi
    
    # 方法2: 使用 tar 文件方式（备用方案）
    log_info "使用备用方法加载镜像..."
    local temp_tar="/tmp/$(echo "$image" | tr '/:' '-').tar"
    
    # 确保镜像存在
    if ! podman image exists "$image"; then
        log_info "拉取镜像 $image..."
        podman pull "$image"
    fi
    
    # 保存为 tar 并加载
    podman save -o "$temp_tar" "$image"
    kind load image-archive "$temp_tar" --name "$cluster_name"
    rm -f "$temp_tar"
    
    log_info "✓ 镜像加载完成"
}

log_info "检查必要工具..."
check_command podman
check_command kind
check_command kubectl

# 1. 创建 Kind 集群
log_info "步骤 1/7: 创建 Kind 集群..."
if kind get clusters | grep -q "k8s-demo"; then
    log_warn "集群 k8s-demo 已存在，删除现有集群..."
    kind delete cluster --name k8s-demo
fi

log_info "创建新的 Kind 集群..."
kind create cluster --config deployment/00-kind-k8s-demo.yaml

# 等待集群就绪
log_info "等待集群就绪..."
kubectl wait --for=condition=Ready nodes --all --timeout=120s

# 2. 安装 Metrics Server
log_info "步骤 2/7: 安装 Metrics Server..."
log_info "将Metrics Server镜像加载到 Kind 集群..."
load_image_to_kind "registry.k8s.io/metrics-server/metrics-server:v0.8.0" "k8s-demo"
kubectl apply -f deployment/00-metrics-server.yaml

log_info "等待 Metrics Server 启动..."
sleep 10

log_info "等待 Metrics Server Pod 就绪..."
kubectl wait --namespace kube-system \
  --for=condition=ready pod \
  --selector=k8s-app=metrics-server \
  --timeout=120s

# 3. 验证 Metrics Server
log_info "步骤 3/7: 验证 Metrics Server..."
log_info "检查 Metrics Server 状态..."
kubectl get pods -n kube-system | grep metrics-server

log_info "等待 Metrics API 可用..."
max_attempts=30
attempt=1
while [ $attempt -le $max_attempts ]; do
    if kubectl get --raw /apis/metrics.k8s.io/v1beta1 2>/dev/null; then
        log_info "Metrics API 已可用"
        break
    fi
    log_info "等待 Metrics API... ($attempt/$max_attempts)"
    sleep 10
    attempt=$((attempt + 1))
done

if [ $attempt -gt $max_attempts ]; then
    log_error "Metrics API 未在预期时间内可用"
    log_info "检查 Metrics Server 日志:"
    kubectl logs -n kube-system -l k8s-app=metrics-server
    exit 1
fi

# 4. 构建应用镜像
log_info "步骤 4/7: 构建应用镜像..."
log_info "构建 Docker 镜像..."
podman build -t localhost/k8s-demo-app:0.0.1 -f app/Dockerfile app/

log_info "验证镜像..."
if ! podman images | grep -q "k8s-demo-app"; then
    log_error "镜像构建失败"
    exit 1
fi

# 5. 加载镜像到 Kind 集群
log_info "步骤 5/7: 加载镜像到 Kind 集群..."
log_info "将镜像加载到 Kind 集群..."
load_image_to_kind "localhost/k8s-demo-app:0.0.1" "k8s-demo"

# 验证镜像已加载
log_info "验证镜像已加载到集群..."
if ! kind get nodes --name k8s-demo | xargs -I {} podman exec {} crictl images | grep -q "k8s-demo-app"; then
    log_error "镜像加载到集群失败"
    exit 1
fi

# 6. 创建命名空间并部署应用
log_info "步骤 6/7: 创建命名空间并部署应用..."
kubectl apply -f deployment/01-namespace.yaml

log_info "部署应用和 HPA..."
kubectl apply -f deployment/02-k8s-demo-app.yaml
kubectl apply -f deployment/03-hpa.yaml

log_info "等待应用 Pod 就绪..."
kubectl wait --namespace k8s-demo \
  --for=condition=ready pod \
  --selector=app=k8s-demo-app \
  --timeout=120s

# 7. 验证部署和监控
log_info "步骤 7/7: 验证部署和监控..."
log_info "等待指标数据可用..."
sleep 30

log_info "测试指标收集..."
if kubectl top nodes 2>/dev/null; then
    log_info "节点指标收集正常"
else
    log_warn "节点指标暂时不可用，继续部署..."
fi

if kubectl top pods -n k8s-demo 2>/dev/null; then
    log_info "Pod 指标收集正常"
else
    log_warn "Pod 指标暂时不可用，HPA 可能需要更多时间..."
fi

# 显示部署状态
log_info "=== 部署状态 ==="
echo -e "\n集群信息:"
kubectl cluster-info

echo -e "\n节点状态:"
kubectl get nodes -o wide

echo -e "\n命名空间:"
kubectl get namespaces k8s-demo

echo -e "\nPod 状态:"
kubectl get pods -n k8s-demo -o wide

echo -e "\n服务状态:"
kubectl get services -n k8s-demo

echo -e "\nHPA 状态:"
kubectl get hpa -n k8s-demo

echo -e "\nMetrics Server 状态:"
kubectl get apiservices v1beta1.metrics.k8s.io

# 获取访问信息
log_info "=== 访问信息 ==="
NODE_IP=$(kubectl get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}')
NODE_PORT=$(kubectl get service k8s-demo-service -n k8s-demo -o jsonpath='{.spec.ports[0].nodePort}')

echo -e "\n访问方式:"
echo "1. 直接访问: http://${NODE_IP}:${NODE_PORT}"
echo "2. 端口转发: kubectl port-forward service/k8s-demo-service -n k8s-demo 8080:80"
echo "3. API 测试: curl http://${NODE_IP}:${NODE_PORT}/api/v1/users"
echo "4. 健康检查: curl http://${NODE_IP}:${NODE_PORT}/health"

echo -e "\n负载均衡测试:"
echo "for i in {1..10}; do curl -s http://${NODE_IP}:${NODE_PORT}/info | grep pod_name; done"

echo -e "\n自动扩展测试:"
echo "kubectl run -it --rm load-test --image=busybox -- /bin/sh -c 'while true; do wget -q -O- http://k8s-demo-service.k8s-demo.svc.cluster.local/cpu-intensive; done'"

log_info "=== 部署完成 ==="
echo -e "\n常用命令:"
echo "查看 Pod 日志: kubectl logs -f -n k8s-demo <pod-name>"
echo "进入 Pod: kubectl exec -it -n k8s-demo <pod-name> -- /bin/sh"
echo "监控 HPA: watch kubectl get hpa -n k8s-demo"
echo "查看 Metrics Server 日志: kubectl logs -n kube-system -l k8s-app=metrics-server"
echo "删除部署: kubectl delete -f deployment/ --recursive"
echo "删除集群: kind delete cluster --name k8s-demo"
